<script setup>
import MarkdownRenderer from './MarkdownRenderer.vue'
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
  message: {
    type: Object,
    required: true
  }
})

const messageContent = ref('')

// 监听消息内容变化
watch(() => props.message.content, (newContent) => {
  messageContent.value = newContent
}, { immediate: true })

const emit = defineEmits(['regenerate'])
const showCopySuccess = ref(false)

const fallbackCopyToClipboard = (text) => {
  // 创建一个临时文本区域
  const textArea = document.createElement('textarea')
  textArea.value = text
  textArea.style.position = 'fixed'
  textArea.style.left = '-9999px'
  textArea.style.top = '0'
  document.body.appendChild(textArea)
  
  try {
    textArea.select()
    textArea.setSelectionRange(0, 99999) // 兼容移动设备
    const successful = document.execCommand('copy')
    if (!successful) throw new Error('Copy command was unsuccessful')
    return true
  } catch (err) {
    console.error('Fallback copy failed:', err)
    return false
  } finally {
    document.body.removeChild(textArea)
  }
}

const copyToClipboard = async () => {
  const textToCopy = messageContent.value
  
  try {
    let success = false
    
    // 首先尝试使用现代 Clipboard API
    if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
      try {
        await navigator.clipboard.writeText(textToCopy)
        success = true
      } catch (err) {
        console.warn('Clipboard API failed, falling back to execCommand:', err)
      }
    }
    
    // 如果现代API失败，使用后备方案
    if (!success) {
      success = fallbackCopyToClipboard(textToCopy)
    }
    
    if (success) {
      showCopySuccess.value = true
      ElMessage({
        message: '复制成功',
        type: 'success',
        duration: 2000,
        offset: 60
      })
      setTimeout(() => {
        showCopySuccess.value = false
      }, 2000)
    } else {
      throw new Error('Copy failed')
    }
  } catch (err) {
    console.error('Failed to copy:', err)
    ElMessage({
      message: '复制失败，请重试',
      type: 'error',
      duration: 2000,
      offset: 60
    })
  }
}
</script>

<template>
  <div :class="['message-container', message.role]">
    <div class="message-content">
      <div class="avatar">
        <img :src="message.role === 'user' ? '/user-avatar.png' : '/bot-avatar.png'" :alt="message.role">
      </div>
      <div class="content">
        <div v-if="message.role === 'user'" class="user-message">
          {{ messageContent }}
        </div>
        <div v-else class="assistant-message">
          <MarkdownRenderer :content="messageContent" />
          <div class="message-actions">
            <button 
              class="action-button" 
              @click="copyToClipboard"
              :title="showCopySuccess ? '已复制!' : '复制'"
            >
              <svg v-if="!showCopySuccess" viewBox="0 0 24 24" class="action-icon">
                <path fill="currentColor" d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/>
              </svg>
              <svg v-else viewBox="0 0 24 24" class="action-icon">
                <path fill="currentColor" d="M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4L9 16.2z"/>
              </svg>
            </button>
            <button 
              v-if="message.role === 'assistant'"
              class="action-button"
              @click="$emit('regenerate')"
              title="重新生成"
            >
              <svg viewBox="0 0 24 24" class="action-icon">
                <path fill="currentColor" d="M17.65 6.35A7.958 7.958 0 0012 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08A5.99 5.99 0 0112 18c-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"/>
              </svg>
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.message-container {
  padding: 1.5rem 1rem;
  display: flex;
  justify-content: center;
}

.message-container.user {
  background: var(--primary-bg);
}

.message-container.assistant {
  background: var(--bot-bg);
}

.message-content {
  display: flex;
  gap: 1rem;
  width: 100%;
  max-width: 48rem;
  margin: 0 auto;
  align-items: flex-start;
}

.avatar {
  width: 30px;
  height: 30px;
  border-radius: 0.25rem;
  overflow: hidden;
  flex-shrink: 0;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.content {
  flex: 1;
  min-width: 0;
  line-height: 1.75;
  padding-right: 30px; /* 添加右侧padding以平衡左侧avatar的宽度 */
}

.user-message {
  white-space: pre-wrap;
}

.message-actions {
  display: flex;
  gap: 0.5rem;
  margin-top: 0.5rem;
  justify-content: flex-end;
}

.action-button {
  padding: 0.25rem;
  background: transparent;
  border: none;
  color: var(--text-secondary);
  cursor: pointer;
  border-radius: 0.25rem;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-button:hover {
  background: rgba(255, 255, 255, 0.1);
  color: var(--text-primary);
}

.action-icon {
  width: 1.25rem;
  height: 1.25rem;
}

@media (max-width: 768px) {
  .message-container {
    padding: 1rem 0.75rem;
  }
  
  .message-content {
    gap: 0.75rem;
  }
  
  .avatar {
    width: 24px;
    height: 24px;
  }
  
  .content {
    padding-right: 24px;
  }
}
</style> 